package com.glodon.ggzy.user.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.glodon.ggzy.entity.ZhRole;
import com.glodon.ggzy.entity.ZhUser;
import com.glodon.ggzy.entity.ZhUserRoleMapper;
import com.glodon.ggzy.user.dao.ISsoRoleDao;
import com.glodon.ggzy.user.dao.ISsoUserDao;
import com.glodon.ggzy.user.dao.ISsoUserRoleMapDao;
import com.glodon.ggzy.user.service.ISsoService;

/**
 * 
 * 
 * SSO服务处理实现类
 * @author supf
 * @since jdk1.6
 * @date 2013-6-17
 *
 */
@Service
@Transactional
public class SsoServiceImpl implements ISsoService {

	@Autowired
	private ISsoUserDao ssoUserDao;

	@Autowired
	private ISsoUserRoleMapDao ssoUserRoleMapDao;

	@Autowired
	private ISsoRoleDao ssoRoleDao;

	@Override
	public boolean isUserExsit(String userName) {
		List<ZhUser> userList = ssoUserDao.findBy("userName", userName);
		if (null != userList && userList.size() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public ZhUser getUser(String userName) {
		List<ZhUser> userList = ssoUserDao.findBy("userName", userName);
		if (null != userList && userList.size() > 0) {
			return userList.get(0);
		}
		return null;
	}

	@Override
	public String getRolesByUserId(String userId) {
		List<ZhUserRoleMapper> mapperList = ssoUserRoleMapDao.findBy("userId", userId);
		StringBuilder roles = new StringBuilder();
		ZhRole role = null;
		for (int i = 0; i < mapperList.size(); i++) {
			role = ssoRoleDao.get(mapperList.get(i).getRoleId());
			if (i == 0) {
				roles.append(role.getRoleCode());
			} else {
				roles.append("," + role.getRoleCode());
			}
		}
		return roles.toString();
	}

	@Override
	public boolean saveUserRole(String userName, String roles) {
		ZhUser user = new ZhUser();
		user.setUserName(userName);
		user.setApproveStatus("APPROVED");
		ssoUserDao.save(user);
		if (StringUtils.isNotEmpty(roles)) {
			String[] rolesArray = {};
			rolesArray = roles.split(",");
			for (int i = 0; i < rolesArray.length; i++) {
				ZhUserRoleMapper userRoleMapper = new ZhUserRoleMapper();
				List<ZhRole> roleList = ssoRoleDao.findBy("roleCode", rolesArray[i]);
				if (null != roleList && roleList.size() > 0) {
					ZhRole role = roleList.get(0);
					userRoleMapper.setRoleId(role.getId());
					userRoleMapper.setUserId(user.getId());
					ssoUserRoleMapDao.save(userRoleMapper);
				} else {
					return false;
				}
			}
		}

		return true;
	}

}
